import { checkPassword, createUser, getUserByUsername, updateUser, updatePassword } from "../../dal/user/UserRepo";
import { LoginCmd, RegisterCmd, UpdatePasswordCmd, UpdateUserCmd, User } from "../../dto";
import { BizError } from "../../enums/ErrorsEnum";
import { signJwtToken } from "../../util/jwt";
import { validateEmptyWithName } from "../../util/validate";

/**
 * 用户登录
 * @param cmd 登录命令对象
 * @returns jwt凭据
 */
export async function login(cmd: LoginCmd) : Promise<string> {
    if (await checkPassword(cmd.username,cmd.password)) {
        return signJwtToken(cmd.username);
    } else throw new BizError("密码错误");
}

/**
 * 用户注册
 * @param cmd  注册命令对象
 */
export async function register(cmd: RegisterCmd) {
    validateEmptyWithName([
        {
            name: "用户名",
            value: cmd.username
        },
        {
            name: "名称",
            value: cmd.name
        },
        {
            name: "密码",
            value: cmd.password
        }
    ])
    if (cmd.password.length < 6) throw new BizError("密码长度至少为6")
    await createUser(cmd);
}

/**
 * 更新用户信息
 * @param cmd 更新命令对象
 * @param username 用户名
 */
export async function update(cmd: UpdateUserCmd,username: string) {
    validateEmptyWithName([
        {
            name: "名称",
            value: cmd.name
        }
    ])
    await updateUser(cmd,username);
}

/**
 * 更新密码
 * @param cmd 更新密码命令对象
 * @param username 用户名
 */
export async function updatePass(cmd: UpdatePasswordCmd,username: string) {
    validateEmptyWithName([{
        name: "新密码",
        value: cmd.newPassword
    }])
    if (cmd.newPassword.length < 6) throw new BizError("新密码长度至少为6")
    if (!(await checkPassword(username,cmd.oldPassword))) throw new BizError("旧密码错误")
    await updatePassword(username,cmd.newPassword);
}

/**
 * 获取用户信息
 * @param username 用户名
 */
export async function getUserInfo(username: string) : Promise<User> {
    return await getUserByUsername(username)
}

